package com.lsh.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.lsh.service.ProviderService;
import com.lsh.service.TxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/3/17 4:16 下午
 * @desc ：
 */
@Service
@Component
public class TxServiceImpl implements TxService {



    @Autowired
    RedisTemplate redisTemplate;

    @Reference
    ProviderService providerService;


    /**
     * 指定序列化方式
     */
    @PostConstruct
    public void init() {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        redisTemplate.setValueSerializer(redisSerializer);
        redisTemplate.setHashKeySerializer(redisSerializer);
        redisTemplate.setHashValueSerializer(redisSerializer);
    }


    @Override
    public void buyAnApple() {

        redisTemplate.opsForValue().decrement("money",100L);
        String money = (String) redisTemplate.opsForValue().get("money");
        System.out.println("==============================");
        System.out.println("消费成功~"+"当前余额："+money+" 元 ");
        System.out.println("开始调用远程服务将库存减一...");
        String s = providerService.minusAppleNum();
        if ("0000".equals(s)){
            System.out.println("库存扣减成功~");
            System.out.println("==============================");
        }else{
            System.out.println("库存扣减失败~");
            System.out.println("==============================");
            throw new RuntimeException("库存扣减失败");
        }


    }
}
